<template>
    <!-- 待处理订单 -->
    <div
        v-if="useOrder.process.length !== 0"
        class="process-container"
        v-loading="loading"
        element-loading-text="正在加载并验证所有待处理订单，请稍后..."
    >
        <!-- 待处理项目 -->
        <div v-for="(item, index) in processData" :key="index" class="w-full mb-2">
            <el-descriptions title="处理项目" :column="5" border direction="vertical">
                <!-- 订单日期 -->
                <el-descriptions-item align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Timer /></el-icon>
                            <el-text type="primary" tag="b">订单日期</el-text>
                        </div>
                    </template>
                    {{ formatTimeZone(item.orderDate, 'YYYY-MM-DD') }}
                </el-descriptions-item>
                <!-- 产品名称 -->
                <el-descriptions-item :rowspan="2" align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Document /></el-icon>
                            <el-text type="primary" tag="b">产品名称</el-text>
                        </div>
                    </template>
                    {{ item.productName }}
                </el-descriptions-item>
                <!-- 客户 -->
                <el-descriptions-item align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Avatar /></el-icon>
                            <el-text type="primary" tag="b">客户</el-text>
                        </div>
                    </template>
                    {{ matchCustomerInfo(item.customerId).customerAbbreviation }}
                </el-descriptions-item>
                <!-- 订单量 -->
                <el-descriptions-item align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Calculator /></el-icon>
                            <el-text type="primary" tag="b">订单量</el-text>
                        </div>
                    </template>
                    {{ item.orderNumber }}
                </el-descriptions-item>
                <!-- 库存 -->
                <el-descriptions-item :rowspan="3" align="center">
                    <template #label>
                        <el-tooltip class="box-item" effect="dark" content="现有库存 + 备用库存 + 在途采购(未生产入库)" placement="top-start">
                            <div class="flex items-center">
                                <el-icon class="mr-2"><House /></el-icon>
                                <el-text type="primary" tag="b">库存</el-text>
                                <el-icon class="ml-2"><ZoomQuestion /></el-icon>
                            </div>
                        </el-tooltip>
                    </template>
                    {{ stockData[index] == null ? '加载中...' : stockData[index] }}
                </el-descriptions-item>
                <!-- 订单号 -->
                <el-descriptions-item align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Paperclip /></el-icon>
                            <el-text type="primary" tag="b">订单号</el-text>
                        </div>
                    </template>
                    {{ item.orderNo }}
                </el-descriptions-item>
                <!-- 订单操作 -->
                <el-descriptions-item align="center" :span="3">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Setting /></el-icon>
                            <el-text type="primary" tag="b">订单操作</el-text>
                        </div>
                    </template>
                    <el-button type="primary" @click="handleOrderPurchaseEvent(item)">下单采购</el-button>
                    <el-button type="primary" @click="handleOrderByStoreEvent">使用库存</el-button>
                    <el-button type="warning" @click="handleDeleteOrderProcessEvent(item.orderNo, item.productName)">删除</el-button>
                </el-descriptions-item>
                <!-- 订单备注 -->
                <el-descriptions-item align="center">
                    <template #label>
                        <div class="flex items-center">
                            <el-icon class="mr-2"><Notebook /></el-icon>
                            <el-text type="primary" tag="b">订单备注</el-text>
                        </div>
                    </template>
                    {{ item.orderRemark ? item.orderRemark : '暂无' }}
                </el-descriptions-item>
            </el-descriptions>
        </div>
        <!-- 分页 -->
        <div class="w-full h-20 flex justify-center items-center">
            <el-pagination v-model:current-page="page" :page-size="2" :total="useOrder.process.length" background layout="prev,pager,next,jumper" />
        </div>
    </div>

    <!-- 空数据 -->
    <el-empty v-if="useOrder.process.length == 0" description="当前没有可用的订单处理" />

    <!-- 下单采购 -->
    <el-dialog v-model="purchaseVisible" :close-on-click-modal="false" width="80%" :show-close="false" draggable top="7vh">
        <!-- 标题 -->
        <template #header="{ close, titleId, titleClass }">
            <div class="my-header">
                <h4 :id="titleId" :class="titleClass">
                    确认采购订单PO：{{ purchaseForm.orderNo }}
                    <el-text type="primary">
                        【{{ purchaseForm.productName }}
                        <el-text type="warning"> x </el-text>
                        {{ purchaseForm.orderNumber }} 只】
                    </el-text>
                </h4>
                <el-button type="danger" @click="close">
                    <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
                    关闭
                </el-button>
            </div>
        </template>
        <!-- 表单 -->
        <el-form ref="purchaseFormRef" class="grid grid-cols-2 gap-1" label-position="top" label-width="auto" :model="purchaseForm" :rules="rules">
            <el-form-item label="客户：" required>
                <el-input v-model="purchaseForm.customerAbbreviation" disabled></el-input>
            </el-form-item>
            <el-form-item label="供应商：" required prop="supplierAbbreviation">
                <el-autocomplete
                    v-model="purchaseForm.supplierAbbreviation"
                    placeholder="请选择供应商"
                    clearable
                    :fetch-suggestions="querySupplierSearch"
                    @select="handleSupplierSelect"
                />
            </el-form-item>
            <el-form-item label="产品名称：" required>
                <el-autocomplete v-model="purchaseForm.productName" :fetch-suggestions="queryProductSearch" clearable @select="handleProductSelect" />
            </el-form-item>
            <el-form-item label="产品尺寸：" required>
                <el-input v-model="purchaseForm.productSize" disabled></el-input>
            </el-form-item>
            <el-form-item label="面纸尺寸（二选一）：">
                <el-input v-model="purchaseForm.tissueSize"></el-input>
            </el-form-item>
            <el-form-item label="瓦楞尺寸（二选一）：">
                <el-input v-model="purchaseForm.corrugatedSize"></el-input>
            </el-form-item>
            <el-form-item label="材质：" required>
                <el-input v-model="purchaseForm.materialQuality"></el-input>
            </el-form-item>
            <el-form-item label="压线：">
                <el-input v-model="purchaseForm.crimping"></el-input>
            </el-form-item>
            <!-- 拼数 / 采购等级 / 备货量 / 采购数量 / 送货地址 -->
            <div class="flex justify-between col-span-2">
                <el-form-item label="拼数：" required>
                    <el-input v-model="purchaseForm.spell" disabled></el-input>
                </el-form-item>
                <el-form-item label="订单状态：" required>
                    <el-select v-model="purchaseForm.orderStatus" placeholder="请选择订单状态" style="width: 200px">
                        <el-option v-for="(item, index) in orderStatusOptions" :key="index" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="采购量：" required>
                    <el-input-number v-model="purchaseForm.purchaseNumber" :min="0" :step="5" />
                </el-form-item>
                <el-form-item label="备货量：" required>
                    <el-input-number v-model="purchaseForm.stockNumber" :min="0" :step="5" />
                </el-form-item>
                <el-form-item label="送货地址：" required prop="arrivalTo">
                    <el-autocomplete v-model="purchaseForm.arrivalTo" placeholder="请选择送货地址" :fetch-suggestions="queryArrivalToSearch" />
                </el-form-item>
            </div>
            <!--  -->
            <el-form-item class="col-span-2" label="订单备注：">
                <el-input type="textarea" v-model="purchaseForm.orderRemark" autosize></el-input>
            </el-form-item>
            <el-form-item class="col-span-2" label="采购备注：" required>
                <el-input type="textarea" v-model="purchaseForm.purchaseNotes" autosize></el-input>
            </el-form-item>
        </el-form>
        <!-- Dialog 按钮操作区的内容 -->
        <div slot="footer" class="w-full text-right">
            <el-button @click="purchaseVisible = false">取消</el-button>
            <el-button type="primary" :loading="creatPurchaseBtnLoading" @click="creatPurchaseEvent(purchaseFormRef)">确定</el-button>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { Timer, Paperclip, Avatar, Document, House, Notebook, Setting, CircleCloseFilled } from '@element-plus/icons-vue';
import { Calculator, ZoomQuestion } from '@vicons/tabler';
import { FormInstance, FormRules } from 'element-plus';
import { useOrderStore } from '@store/modules/order';
import { useUserStore } from '@/store/modules/user';
import { formatTimeZone } from '@utils/calculate/index';
import { checkPermi } from '@utils/permission';
import { getCustomerList } from '@api/customer';
import { getProductInfo, getProductList, getProductStock } from '@api/product';
import { getSupplierList } from '@/api/supplier';
import { createPurchase } from '@api/purchase';
import { useSystemStore } from '@/store/modules/system';
import { checkProcessValidate } from '@/api/process';

onMounted(async () => {
    const validate = await checkProcessValidateEvent();
    // 获取流程验证结果然后再加载客户/供应商数据
    if (validate) {
        loading.value = false;
        updateCustomerList();
        updateSupplierList();
    }
});

/* ******************************通用属性/方法****************************** */
// order的store
const useOrder = useOrderStore();
// user的store
const useUser = useUserStore();
// system的store
const system = useSystemStore();
// 路由
const router = useRouter();

/* ******************************客户/供应商/产品列表属性/方法****************************** */
// 客户列表
const customerList = reactive<AjaxResponse['customerList']>([]);
// 查询所有激活的用户
const updateCustomerList = async () => {
    getCustomerList(true).then((res) => {
        res.data.forEach((item) => customerList.push(item));
    });
};
// 匹配客户列表 -- 通过客户id
const matchCustomerInfo = (id: string): { customerName: string; customerAbbreviation: string } => {
    const obj: { customerName: string; customerAbbreviation: string } = {
        customerName: '未知',
        customerAbbreviation: '未知',
    };
    for (let index = 0; index < customerList.length; index++) {
        const customer = customerList[index];
        if (customer._id == id) {
            obj.customerName = customer.customerName;
            obj.customerAbbreviation = customer.customerAbbreviation;
            break;
        }
    }
    return obj;
};
// 供应商列表
const supplierList = reactive<AjaxResponse['supplierList']>([]);
// 查询所有激活的供应商
const updateSupplierList = async () => {
    getSupplierList(true).then((res) => {
        res.data.forEach((item) => {
            item.value = item.supplierAbbreviation;
            supplierList.push(item);
        });
    });
};

// 产品列表
const productList = reactive<AjaxResponse['productList']>([]);

/* ******************************订单分页&&产品库存--属性/方法****************************** */
// 分页页码
const page = ref(1);
// 当前两款待处理库存
const stockData = reactive<any[]>([null, null]);
// 当前需要处理的两个订单
const processData = computed(() => {
    try {
        // 每次计算时，清空库存数据
        stockData.length = 0;
        // 计算起始位置和结束为止
        const startIndex = page.value * 2 - 2;
        const endIndex = page.value * 2;
        // 从localstrong中的订单获取数据
        if (useOrder.process.slice(startIndex, endIndex).length >= 1) {
            getProductStock(useOrder.process[startIndex].customerId, useOrder.process[startIndex].productId).then((res) => {
                stockData.push('库存：' + res.data + ' | 在途(未生产)：' + res.purchase.reduce((acc, cur) => acc + cur.purchaseNumber, 0));
            });
        }
        if (useOrder.process.slice(startIndex, endIndex).length >= 2) {
            getProductStock(useOrder.process[startIndex + 1].customerId, useOrder.process[startIndex + 1].productId).then((res) => {
                stockData.push('库存：' + res.data + ' | 在途(未生产)：' + res.purchase.reduce((acc, cur) => acc + cur.purchaseNumber, 0));
            });
        }
        return useOrder.process.slice(startIndex, endIndex);
    } catch (error) {
        console.warn(error);
    }
});

/* ******************************验证未处理订单是否合法的属性/方法****************************** */
// 加载中
const loading = ref(true);
// 检测订单是否存在
const checkProcessValidateEvent = async () => {
    if (processData.value?.length == 0) {
        return false;
    }

    if (processData.value?.length == 1) {
        const { message, data } = await checkProcessValidate(processData!.value[0].orderNo);
        ElMessage({
            type: 'info',
            message,
            grouping: true,
        });
        for (let index = 0; index < data.length; index++) {
            const orderNo = data[index];
            const i = useOrder.process.findIndex((item) => item.orderNo == orderNo);
            if (i != -1) {
                useOrder.process.splice(i, 1);
            }
        }
        return true;
    }

    if (processData.value?.length == 2) {
        const { message, data } = await checkProcessValidate(processData!.value[0].orderNo);
        ElMessage({
            type: 'info',
            message,
            grouping: true,
        });
        for (let index = 0; index < data.length; index++) {
            const orderNo = data[index];
            const i = useOrder.process.findIndex((item) => item.orderNo == orderNo);
            if (i != -1) {
                useOrder.process.splice(i, 1);
            }
        }
        return true;
    }
};

/* ******************************订单选项属性/方法****************************** */
// 打开订单采购dialog -- 处理基本数据/加载产品数据
const handleOrderPurchaseEvent = async (item: (typeof useOrder.process)[0]) => {
    // 权限验证
    if (!checkPermi(['purchase:create'])) {
        ElMessage({
            type: 'warning',
            message: '您没有权限进行此操作！',
        });
    }
    // 请求产品库
    const { code, data } = await getProductInfo(item.customerId, item.productId);
    if (code == 201) {
        ElMessage({
            type: 'warning',
            message: data.message,
            grouping: true,
        });
        return;
    }
    // 订单采购表单数据
    purchaseForm.customerId = item.customerId;
    purchaseForm.customerAbbreviation = matchCustomerInfo(item.customerId).customerAbbreviation;
    purchaseForm.orderNo = item.orderNo;
    purchaseForm.productName = data.productName;
    purchaseForm.productId = item.productId;
    purchaseForm.productSize = data.productSize;
    purchaseForm.tissueSize = data.tissueSize;
    purchaseForm.corrugatedSize = data.corrugatedSize;
    purchaseForm.materialQuality = data.materialQuality;
    purchaseForm.crimping = data.crimping;
    purchaseForm.spell = data.spell;
    purchaseForm.orderNumber = item.orderNumber;
    purchaseForm.purchaseNumber = Math.ceil(item.orderNumber / data.spell);
    purchaseForm.orderRemark = item.orderRemark;
    purchaseForm.purchaseNotes = '订单号：' + item.orderNo + '\r\n' + '订单数量：' + item.orderNumber;
    purchaseForm.orderDeliveryDate = item.orderDeliveryDate;
    purchaseForm.creator = useUser.username;
    purchaseForm.creatorId = useUser.id;
    // 打开订单采购dialog
    purchaseVisible.value = true;

    // 查询所有激活的产品
    productList.length = 0;
    getProductList(item.customerId).then((res) => {
        res.data.forEach((item) => {
            item.value = item.productName;
            productList.push(item);
        });
    });
};
// 使用库存纸生产订单
const handleOrderByStoreEvent = () => {
    router.push({ path: '/order/stock' });
};
// 删除单个订单处理
const handleDeleteOrderProcessEvent = (orderNo: string, productName: string) => {
    ElMessageBox.confirm('确定要删除该订单处理吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            useOrder.deleteOrderProcess(orderNo, productName);
        })
        .catch(() => {});
};

/* ******************************添加采购选项属性/方法****************************** */
// 采购dialog显示
const purchaseVisible = ref(false);

// 表单ref
const purchaseFormRef = ref();
// 采购表单
const purchaseForm = reactive<AjaxRequest['purchaseForm']>({
    customerId: '',
    customerAbbreviation: '',
    supplierId: '',
    supplierAbbreviation: '',
    orderStatus: 'primary',
    orderNo: '',
    productName: '',
    productId: '',
    productSize: '',
    tissueSize: '',
    corrugatedSize: '',
    materialQuality: '',
    crimping: '',
    spell: 0,
    orderNumber: 0,
    purchaseNumber: 0,
    stockNumber: 0,
    arrivalTo: '',
    orderRemark: '',
    purchaseNotes: '',
    orderDeliveryDate: '',
    creator: '',
    creatorId: '',
});
// 采购等级
const orderStatusOptions = [
    { label: '正常', value: 'primary' },
    { label: '加急', value: 'warning' },
    { label: '特急', value: 'danger' },
];
// 采购表单校验规则
const rules = reactive<FormRules<typeof purchaseForm>>({
    supplierAbbreviation: [{ required: true, message: '请选择供应商' }],
    arrivalTo: [{ required: true, message: '请选择到货地址' }],
});

// 供应商列表搜索
const querySupplierSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (supplier: (typeof supplierList)[0]) => {
            return new RegExp(queryString).test(supplier.supplierName);
        };
    };

    const results = queryString ? supplierList.filter(createFilter(queryString)) : supplierList;
    // call callback function to return suggestions
    cb(results);
};
// 选择供应商时的回调
const handleSupplierSelect = (item: any) => {
    purchaseForm.supplierId = item._id;
};

// 产品列表搜索
const queryProductSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (product: AjaxResponse['productList'][0]) => {
            // 正则处理特殊符号
            const regex = /[.*+?^${}()|[\]\\]/;
            const match = queryString.replace(regex, '\\$&');
            const reg = new RegExp(match, 'i');
            if (reg.test(product.productName)) {
                return true;
            }
        };
    };
    const results = queryString ? productList.filter(createFilter(queryString)) : productList;
    // call callback function to return suggestions
    cb(results);
};
// 选择产品时的回调
const handleProductSelect = (item: any) => {
    purchaseForm.productName = item.productName;
    purchaseForm.productId = item._id;
    purchaseForm.productSize = item.productSize;
    purchaseForm.tissueSize = item.tissueSize;
    purchaseForm.corrugatedSize = item.corrugatedSize;
    purchaseForm.materialQuality = item.materialQuality;
    purchaseForm.crimping = item.crimping;
    purchaseForm.spell = item.spell;
};

// 到货地址搜索
const queryArrivalToSearch = (queryString: string, cb: any) => {
    // 过滤器
    const createFilter = (queryString: string) => {
        return (arrival: (typeof arrivalToArray)[0]) => {
            return new RegExp(queryString).test(arrival.value);
        };
    };

    if (system.purchase.deliveryAddress.length == 0) {
        ElMessage.warning('系统采购配置信息为空，请先配置！方便后续下单！');
    }

    // 创建数据
    const arrivalToArray: any[] = [];
    // 从系统配置中，添加数据
    system.purchase.deliveryAddress.forEach((item) => {
        arrivalToArray.push({
            label: item,
            value: item,
        });
    });
    const results = queryString ? arrivalToArray.filter(createFilter(queryString)) : arrivalToArray;
    // call callback function to return suggestions
    cb(results);
};

// 提交采购订单
const creatPurchaseBtnLoading = ref(false);
// 验证并创建采购订单
const creatPurchaseEvent = (formEl: FormInstance | undefined) => {
    // 表单为空
    if (!formEl) return;
    // 面纸规格和瓦楞规格二选一
    if (purchaseForm.tissueSize !== '' && purchaseForm.corrugatedSize !== '') {
        ElMessage.warning('请正确选择面纸规格和瓦楞规格，只能填写其一！');
        return;
    }
    // 表单校验通过
    creatPurchaseBtnLoading.value = true;
    formEl.validate((valid) => {
        // 表单验证通过
        if (valid) {
            createPurchase(false, purchaseForm).then((res) => {
                // 服务器查询到该订单并验证
                if (res.code == 201) {
                    // 重复添加采购
                    ElMessageBox.confirm(res.message, '采购提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    })
                        .then(() => {
                            // 再次添加
                            createPurchase(true, purchaseForm).then((res) => {
                                creatPurchaseBtnLoading.value = false;
                                purchaseVisible.value = false;
                                useOrder.deleteOrderProcess(purchaseForm.orderNo, purchaseForm.productName);
                                ElMessage.success(res.message);
                            });
                        })
                        .catch(() => {
                            creatPurchaseBtnLoading.value = false;
                        });
                } else {
                    // 添加成功
                    creatPurchaseBtnLoading.value = false;
                    purchaseVisible.value = false;
                    useOrder.deleteOrderProcess(purchaseForm.orderNo, purchaseForm.productName);
                    ElMessage.success(res.message);
                }
            });
        } else {
            creatPurchaseBtnLoading.value = false;
        }
    });
};
</script>

<style scoped lang="scss">
.process-container {
    height: calc(100vh - 80px);
    display: flex;
    flex-wrap: wrap;
    align-content: space-between;
    justify-content: center;
}
.my-header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 16px;
}
</style>
